import React, { useEffect, useState } from 'react'
import { Modal, message, Skeleton } from 'antd'
import ProForm, { ProFormText } from '@ant-design/pro-form'
import { updateUser, showUser } from '@/services/user' 


export default function Edit(props) {

  const { isModalVisibleEdit, isShowModalEdit, actionRef, editId } = props

  let [initialValues, setInitialValues] = useState(undefined)

  useEffect(async () => {
    // 获取用户详情
    if(editId !== undefined) {
      const response = await showUser(editId)
      setInitialValues({
        name: response.name,
        email: response.email
      })
    }
  }, [])

  // 点击提交 修改用户信息
  const editUser = async values => {
    // 发送请求，修改用户信息
    const response = await updateUser(editId, values)
    if(response.status === undefined) {
      message.success('编辑用户成功!')
      // 刷新表格
      actionRef.current.reload()
      isShowModalEdit(false)
    } else {
      message.error('添加用户失败!')
    }
  }

  return (
    <Modal title="编辑用户" visible={isModalVisibleEdit} onCancel={() => {isShowModalEdit(false)}} footer={null} destroyOnClose={true}>
      {
        initialValues === undefined ? <Skeleton active paragraph={{ rows: 4 }} /> :
        <ProForm
          onFinish={ (values) => editUser(values) }
          initialValues={ initialValues }
        >
          <ProFormText
            name="name"
            label="昵称"
            placeholder="请输入昵称"
            rules={[
              { required: true, message: '请输入昵称!' }
            ]}
          />
          <ProFormText
            name="email"
            label="邮箱"
            placeholder="请输入邮箱"
            rules={[
              { required: true, message: '请输入邮箱!' },
              { type: 'email', message: '邮箱格式不正确!' }
            ]}
          />
        </ProForm>
      }
    </Modal>
  )
}
